//
//  LikeButton.m
//  AnimationDemo
//
//  Created by Jiaozl 2018 on 2018/9/12.
//  Copyright © 2018年 Jiaozl. All rights reserved.
//

#import "LikeButton.h"

@interface LikeButton()

@property (nonatomic, strong) CAEmitterLayer * explosionLayer;

@end

@implementation LikeButton

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self setupExplosion];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self=[super initWithFrame:frame]) {
        [self setupExplosion];
    }
    return self;
}

- (void)setupExplosion {
    
    // 1. 粒子
    CAEmitterCell *explosionCell = [CAEmitterCell emitterCell];
    explosionCell.name = @"explosionCell";
    explosionCell.alphaSpeed = -1.f;
    explosionCell.alphaRange = .1f;
    explosionCell.lifetime = 1.f;
    explosionCell.lifetimeRange = .1f;
    explosionCell.velocity = 40.f;
    explosionCell.velocityRange = 10.f;
    explosionCell.scale = 0.08;
    explosionCell.scaleRange = 0.02;
    explosionCell.contents = (id)[[UIImage imageNamed:@"spark_red"] CGImage];
    
    // 2. 发射源
    CAEmitterLayer *explosionLayer = [CAEmitterLayer layer];
    [self.layer addSublayer:explosionLayer];
    self.explosionLayer = explosionLayer;
    explosionLayer.emitterSize = CGSizeMake(self.bounds.size.width*1.5, self.bounds.size.height*1.5);
    explosionLayer.emitterShape = kCAEmitterLayerCircle;
    explosionLayer.emitterMode = kCAEmitterLayerOutline;
    explosionLayer.renderMode = kCAEmitterLayerOldestFirst;
    explosionLayer.emitterCells = @[explosionCell];
}

- (void)layoutSubviews {
    // 发射源位置
    self.explosionLayer.position = CGPointMake(self.bounds.size.width*0.5, self.bounds.size.height*0.5);
    
    [super layoutSubviews];
}

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];
    
    // 关键帧动画实现缩放
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    
    if(selected) { // 没有点击到点击状态
        animation.values = @[@1.5, @2.0, @0.8, @1.0];
        animation.duration = 0.5;
        animation.calculationMode = kCAAnimationCubic;
        [self.layer addAnimation:animation forKey:nil];
        
        [self performSelector:@selector(startAnimation) withObject:nil afterDelay:0.25];
    } else { // 点击到未点击状态
        [self stopAnimation];
    }
    
}

/**
 * 开始动画
 */
- (void)startAnimation {
    [self.explosionLayer setValue:@1000 forKeyPath:@"emitterCells.explosionCell.birthRate"];
    
    // 开始动画
    self.explosionLayer.beginTime = CACurrentMediaTime();
 
    [self performSelector:@selector(stopAnimation) withObject:nil afterDelay:0.15];
}
/**
 * 动画结束
 */
- (void)stopAnimation {
    // 用KVC设置颗粒个数
    [self.explosionLayer setValue:@0 forKeyPath:@"emitterCells.explosionCell.birthRate"];
    [self.explosionLayer removeAllAnimations];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}


@end
